import cn from 'classnames';
import PropTypes from 'prop-types';
import React, { useEffect } from 'react';
import {
	Search24 as SearchIcon,
	ChevronDown16 as ChevronDown,
} from '@carbon/icons-react';
import { withRouter } from 'react-router';
import Input from '@kuiper-components/input';
import Button from '@kuiper-components/button';
import Select, { Option } from '@kuiper-components/select';
import s from './style.module.css';
import Table from '@knownsec/react-component/dist/Table';

import fetchFer from 'API/fetch';
import Pagination from '@knownsec/react-component/dist/Pagination';
import { turnToUrlparam } from '../../../../helpers/getUrlParams';
import confirm from '../../../../components/confirm';
import Tooltip from '@kuiper-components/tooltip';
import Progress from '@knownsec/react-component/dist/Progress';
// import Icon from '@knownsec/react-component/dist/Icon';
import { Link } from 'react-router-dom';
import { Menu, Dropdown } from 'antd';
import notification from '@kuiper-components/notification';
import { datetime } from '../../../../../common/formatter';
import { filterNull } from '../../../../../common/validation/common';
import CopyBoard from '../../../../components/CopyBoard';

import EmptyData from '../../../../components/empty/EmptyData';

import Icon from '../../Detail/icon';
const monitorStatus = {
	waiting: '等待调度',
	active: '正在检测',
	completed: '检测完成',
	failed: '检测失败',
	stopped: '检测停止',
	unkonwn: '未知',
};
let set = null;
function Tablev6({
	className,
	onAgainTask,
	history,
	searchData,
	changeTable,
	statusChange,
}) {
	const [filter, setFilter] = React.useState(searchData);
	const [selectedRows, setSelectedRows] = React.useState([]);
	const [isContinue, setIsContinue] = React.useState(false);
	const [tableData, setTableData] = React.useState({
		data: [],
		total: 0,
	});
	const onSelectChange = newSelectedRowKeys => {
		setSelectedRows(newSelectedRowKeys);
	};
	const statusFun = (cur, item) => {
		const status = item.status;
		return (
			<Tooltip
				overlay={
					<div>
						检测完成时间：
						{status === 'completed' ? datetime(item.endTime) : '- -'}
					</div>
				}
				placement={'top'}
			>
				<div>
					{status === 'completed' ? (
						cur ? (
							<span className={s.supBox}>
								<Icon active={5} />
								<span className={cn(s.successerror, s.vam, s.ml10)}>
									支持IPv6
								</span>
							</span>
						) : (
							<span className={s.supBox}>
								<Icon active={6} />
								<span className={cn(s.errorcolor, s.vam, s.ml10)}>
									不支持IPv6
								</span>
							</span>
						)
					) : (
						'- -'
					)}
				</div>
			</Tooltip>
		);
	};
	const columns = [
		{
			title: '任务名称',
			key: 'name',
			dataIndex: 'name',
			render(e) {
				return <CopyBoard className={s.affect} text={e} />;
			},
		},
		{
			title: '资产地址',
			key: 'target',
			dataIndex: 'target',
			width: 300,
			render(e) {
				return <CopyBoard className={s.affect} text={e} />;
			},
		},
		{
			title: '检测开始时间',
			key: 'startTime',
			dataIndex: 'startTime',
			render(cur) {
				return datetime(cur);
			},
		},
		{
			title: '检测状态',
			key: 'progress',
			dataIndex: 'progress',
			render(cur, row) {
				return (
					<div className={cn(s.df, s.aic)}>
						<span className={cn(s.dotSpan, s[row.status])}></span>
						<span className="ml8">{monitorStatus[row.status]}</span>
					</div>
				);
			},
		},
		{
			title: '合规状态',
			key: 'is_support_ipv6',
			dataIndex: 'is_support_ipv6',
			width: 130,
			render(cur, item) {
				return statusFun(cur, item);
			},
		},
		{
			title: '检测评分',
			key: 'score',
			dataIndex: 'score',
			width: 130,
			render(cur, item) {
				return <span>{item.status === 'completed' ? cur + '分' : '- -'}</span>;
			},
		},
		{
			title: '操作',
			key: 'operate',
			dataIndex: 'operate',
			render(cur, row) {
				const id = row.oid;
				const atid = row.task_session_id;
				const monitorType = ['waiting', 'active'];
				const status = row.status;

				return (
					<div className={s.controlContainer}>
						<div className={s.control}>
							{status === 'completed' && (
								<Link
									to={`/job-manage/ipv6-monitor/detail/${atid}`}
									className={s.item}
								>
									检测结果
								</Link>
							)}
							<Dropdown
								// visible={true}
								overlay={
									<Menu>
										{monitorType.includes(row.status) && (
											<Menu.Item key="1">
												<span
													className={s.itemSpan}
													onClick={() => {
														window._hmt &&
															window._hmt.push([
																'_trackEvent',
																'IPv6',
																'停止任务',
															]);
														stopItem([id]);
													}}
												>
													停止
												</span>
											</Menu.Item>
										)}
										{row.status === 'stopped' && (
											<Menu.Item key="3">
												<span
													className={s.itemSpan}
													onClick={() => {
														window._hmt &&
															window._hmt.push([
																'_trackEvent',
																'IPv6',
																'重试任务',
															]);
														repeatTask([id]);
													}}
												>
													重试
												</span>
											</Menu.Item>
										)}
										{row.status === 'completed' && (
											<Menu.Item key="3">
												<span
													className={s.itemSpan}
													onClick={() => {
														window._hmt &&
															window._hmt.push([
																'_trackEvent',
																'IPv6',
																'再次检测',
															]);
														againTask(row);
													}}
												>
													再次检测
												</span>
											</Menu.Item>
										)}
										<Menu.Item key="2">
											<span
												className={s.itemSpan}
												onClick={() => {
													window._hmt &&
														window._hmt.push(['_trackEvent', 'IPv6', '删除']);
													deleteItem([id]);
												}}
											>
												删除
											</span>
										</Menu.Item>
									</Menu>
								}
								trigger={['click']}
								getPopupContainer={triggerNode => triggerNode.parentElement}
							>
								<a className={s.dropdown} onClick={e => e.preventDefault()}>
									管理
									<ChevronDown />
								</a>
							</Dropdown>
						</div>
					</div>
				);
			},
		},
	];
	const againTask = row => {
		confirm.warning({
			message: `您确定要再次检测所选任务？`,
			okText: '确定',
			cancelText: '取消',
			title: '',
			onOk: () => {
				onAgainTask({
					name: row.name,
					jobIds: [row.jobId],
				});
			},
		});
	};
	const repeatTask = async ids => {
		confirm.warning({
			message: `您确定要重新下发所选检测任务？`,
			okText: '重试',
			cancelText: '取消',
			title: '',
			onCancel: () => {
				setSelectedRows([]);
			},
			onOk: async () => {
				const res = await fetchFer(`/api/v2/tasks/retry`, {
					method: 'POST',
					body: JSON.stringify({ ids }),
					checkStatus: 501,
				}).catch(err => {
					return err;
				});
				if (res.code === 200) {
					notification.success({
						placement: 'top',
						message: `操作成功`,
					});
					getData();
				} else {
					notification.error({
						message: '操作失败',
						description: res.msg,
						placement: 'top',
					});
				}
				setSelectedRows([]);
			},
		});
	};
	const stopItem = ids => {
		confirm.warning({
			message: `您确定要停止所选检测任务？`,
			okText: '停止',
			cancelText: '取消',
			title: '',
			onCancel: () => {},
			onOk: async () => {
				const res = await fetchFer(`/api/v2/tasks/stop`, {
					method: 'POST',
					body: JSON.stringify({ ids }),
				});
				if (res.code === 200) {
					notification.success({
						placement: 'top',
						message: `操作成功`,
					});
					getData();
				} else {
					notification.error({
						message: '操作失败',
						placement: 'top',
					});
				}
			},
		});
	};
	const deleteItem = id => {
		const ids = id || selectedRows;
		confirm.warning({
			message: `您确定要删除所选检测任务？`,
			okText: '确定',
			cancelText: '取消',
			title: '',
			onCancel: () => {
				setSelectedRows([]);
			},
			onOk: async () => {
				const res = await fetchFer(`/api/v2/tasks/delete`, {
					method: 'POST',
					body: JSON.stringify({ ids }),
					checkStatus: 501,
				}).catch(err => {
					console.log(err);
					return {};
				});
				if (res.code === 200) {
					notification.success({
						placement: 'top',
						message: `删除成功`,
					});
					getData();
					statusChange();
				} else {
					notification.error({
						message: '删除失败',
						placement: 'top',
					});
				}
				setSelectedRows([]);
			},
		});
	};
	const getData = async e => {
		const sendData = { ...searchData, ...e };
		const params = turnToUrlparam(sendData);
		const res = await fetchFer(`/api/v2/tasks/ipv6/list?${params}`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(error => {
			console.log('[ error ]-222', error);
			return error;
		});
		if (res.code !== 200 && sendData.page > 1) {
			handleChangeSearch({ limit: 10, page: sendData.page - 1 });
			return false;
		}
		const listData = res.results.data.map(item => {
			return { ...item, key: item.oid };
		});
		const some = res.results.data.some(row => {
			if (row.status === 'waiting' || row.status === 'active') {
				return true;
			}
		});
		setIsContinue(some);
		setTableData({ data: listData, total: res.results?.total });
	};
	const handleChangeSearch = e => {
		let filter_ = null;
		if (e && e.page) {
			filter_ = filterNull({ ...filter, ...e });
		} else {
			filter_ =
				e === 'r' ? {} : filterNull({ ...filter, ...e, page: 1, limit: 10 });
		}
		const backparams = JSON.stringify(filter_);
		const searchString = 'filter=' + encodeURI(backparams);
		history.replace(`/job-manage/ipv6-monitor?${searchString}`);
	};
	// 轮询状态
	useEffect(() => {
		if (isContinue) {
			setIsContinue(false);
			clearTimeout(set);
			set = setTimeout(() => {
				getData();
				statusChange();
			}, 3000);
		}
	}, [isContinue]);
	useEffect(() => {
		getData();
		setFilter(searchData);
	}, [searchData, changeTable]);
	return (
		<>
			<div className={cn(className, s.monitorToolbox)}>
				<Input
					className={s.input}
					type="search"
					placeholder="请输入资产地址"
					value={filter.target}
					onChange={target => {
						setFilter({ ...filter, target });
					}}
					onPressEnter={() => {
						handleChangeSearch();
					}}
					after={
						<SearchIcon
							className={s.searchIcon}
							onClick={() => {
								handleChangeSearch();
							}}
						/>
					}
				/>
				<div className={s.selectContainer}>
					<Select
						placeholder="检测状态"
						className={s.select}
						value={filter?.status}
						getPopupContainer={triggerNode => triggerNode}
						onChange={status => {
							handleChangeSearch({ status });
						}}
					>
						<Option value={'waiting'}>等待调度</Option>
						<Option value={'active'}>正在检测</Option>
						<Option value={'completed'}>检测完成</Option>
						<Option value={'stopped'}>检测停止</Option>
					</Select>
					<Select
						placeholder="合规状态"
						className={s.select}
						value={filter?.is_support_ipv6}
						getPopupContainer={triggerNode => triggerNode}
						onChange={is_support_ipv6 => {
							handleChangeSearch({ is_support_ipv6 });
						}}
					>
						<Option value={true}>支持IPv6</Option>
						<Option value={false}>不支持IPv6</Option>
					</Select>
					<Button
						onClick={() => {
							handleChangeSearch('r');
						}}
					>
						重置
					</Button>
				</div>
			</div>
			<Table
				className={s.tableV6}
				rowSelection={{
					selectedRowKeys: selectedRows,
					onChange: onSelectChange,
				}}
				columns={columns}
				data={tableData.data}
				pro
				empty={<EmptyData type={'img'} className={s.nobor} />}
			/>
			<div className={s.bottom}>
				<Button
					link
					disabled={!selectedRows.length}
					className={{ [s.highLight]: selectedRows.length }}
					onClick={() => {
						deleteItem();
					}}
				>
					批量删除
				</Button>
				{tableData.total > 10 && (
					<Pagination
						total={tableData.total}
						current={filter?.page || 1}
						limit={filter?.limit || 10}
						pageSizeOptions={[10, 20, 50]}
						showSizeChanger
						showQuickJumper
						showTotal={total => `共${total}条`}
						onChange={(page, limit) => {
							handleChangeSearch({ page, limit });
						}}
					/>
				)}
			</div>
		</>
	);
}

Tablev6.propTypes = {
	className: PropTypes.string,
	history: PropTypes.any,
	searchData: PropTypes.any,
	onChange: PropTypes.func,
	statusChange: PropTypes.func,
	changeTable: PropTypes.any,
	onAgainTask: PropTypes.func,
};
Tablev6.defaultProps = {
	className: '',
};

export default withRouter(Tablev6);
